var express = require('express');
const login = express.Router();
var bodyParser = require('body-parser');
const path = require("path");
const Database = require("better-sqlite3");
//获取数据库中管理员账号密码等信息
const mydb = new Database(path.resolve(__dirname,"../database/infor.db"), { verbose: console.log });

// 创建 application/x-www-form-urlencoded 编码解析
login.use(bodyParser.urlencoded({ extended: false }))
login.use(express.json());
login.use(bodyParser.json());

login.post('/process_post', function (req, res) {
  // 输出 JSON 格式
  var response = {
    "id": req.body.username,
    "pwd": req.body.password
  };
  console.log(response.id);
  console.log(response.pwd);
  // 判断登录是否成功

  //指定数据库文件路径
  const get_user_by_id = mydb.prepare('SELECT * FROM admin WHERE admin_id= ? and admin_password=?');//一个查询语句对象
  var a = get_user_by_id.get(response.id, response.pwd)//执行查询
  // console.log(a)
  if (a) {
    console.log('登录成功');
    // 登陆成功则跳转到管理页面
    res.sendFile(path.resolve(__dirname,"../public/html/main.html"));
  }
  else {
    console.log('登录失败');
    // 登录失败，则返回登陆界面
    res.sendFile(path.resolve(__dirname,"../public/html/error.html"));
  }
})

// 使用module.exprots导出路由对象
module.exports = login;